package com.briup.estore.web.servlet;

import com.briup.estore.bean.OrderForm;
import com.briup.estore.service.OrderService;
import com.briup.estore.service.ShopCartService;
import com.briup.estore.service.impl.OrderServiceImpl;
import com.briup.estore.service.impl.ShopCartServiceImpl;
import com.briup.estore.util.CommonUtil;
import com.briup.estore.vm.BookVM1;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/commitOrder")
public class CommitOrderServlet extends HttpServlet {

    private ShopCartService shopCartService;
    private OrderService orderService;

    {
        shopCartService = new ShopCartServiceImpl();
        orderService = new OrderServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String cost = req.getParameter("cost");
        String shipAddId = req.getParameter("shipAddId");
        Integer userId = CommonUtil.getUserId(req);

        // 构建OrderForm对象
        OrderForm orderForm = new OrderForm();
        orderForm.setCost(Double.parseDouble(cost));
        orderForm.setCustomerId(userId);
        orderForm.setShopaddressId(Integer.parseInt(shipAddId));
        orderForm.setOrderdate(new Date());

        // 获得确认订单的时候的session数据
        HttpSession session = req.getSession();
        List<BookVM1> bookVmList = (List<BookVM1>)session.getAttribute("bookVmList");

        // 编写逻辑
        // 订单表里加数据
        Integer formId = orderService.addOrderForm(orderForm);
        // 订单项表里加数据
        orderService.addOrderLine(formId,bookVmList);
        // 购物车表里删除数据
        shopCartService.removeFromShopCart(userId,bookVmList);

        // 查询所有订单，渲染在页面上
        List<OrderForm> allOrderForm = orderService.findAllOrderForm(userId);
        session.setAttribute("allOrderForm",allOrderForm);


        resp.sendRedirect("orderList");
    }
}
